package idea.think;

import idea.think.adapter.AllIdeaAdapter;
import idea.think.adapter.CustomAdapter;
import idea.think.adapter.CustomIdeaAdapter;
import idea.think.common.Global;
import idea.think.custom_ui.CustomDialogFragment;
import idea.think.custom_ui.CustomToast;
import idea.think.db.IT_sql;
import idea.think.vo.AllIdea;
import idea.think.vo.Data;
import idea.think.vo.IdeaData;

import java.util.ArrayList;
import java.util.List;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.FragmentManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

@TargetApi(11)
public class IdeaAll extends Activity implements SensorEventListener{
	
	private CustomAdapter adapter;
	private CustomIdeaAdapter ideaAdapter;
	private AllIdeaAdapter allAdapter;
	private SimpleCursorAdapter simpleAdapter;
	
	/* DataBase */
	private IT_sql sql;
	private SQLiteDatabase db;
	private Cursor c;
	private Cursor c3; 			//다이얼로그 아이디어 커서
	private Cursor cursor2; 	//다이얼로그 카테고리 커서 
	private Cursor cateCursor;	//카테고리에 뿌려질 카테고리 커서
	
	/* Component */
	private Spinner mSpin;
	private EditText edit;
	private TextView dText;
	private ImageView mImgBtn01, mImgBtn02, mImgBtn03;
	private ListView mListIdeaView;
	private ListView ideaList;
	private ListView cateList;
	private LinearLayout ideaLayout;
	private LinearLayout cateLayout;
	
	private ArrayList<Data> mCateArray = new ArrayList<Data>();
	private ArrayList<IdeaData> mIdeaArray = new ArrayList<IdeaData>();
	private ArrayList<AllIdea> mAllIdeaArray = new ArrayList<AllIdea>();
	private ArrayList<String> aListCategory = new ArrayList<String>();
	private ArrayList<String> nateSearch = new ArrayList<String>(3);
	
	protected int spinCheck = 0;	
	private SensorManager sensorManager = null;

	FragmentManager manager = null;
	private CustomDialogFragment dialog = null;
	private Context mContext = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {		
		super.onCreate(savedInstanceState);
		
		//sensorManager 생성
		sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
		setContentView(R.layout.all_idea);
		
		mContext = this;
		manager = getFragmentManager();
		
		/* DB Open */
		sql = new IT_sql(this);		
		db = sql.getWritableDatabase();
		
		init();
		setEvent();
		initDataBase();
		new CustomToast(this, "단말기를 흔들어 주세요.").show();
	}
	
	private void init(){
		mListIdeaView = (ListView) findViewById(R.id.all_Idea_ListView);
		mImgBtn01 = (ImageView) findViewById(R.id.idea_admin);
		mImgBtn02 = (ImageView) findViewById(R.id.cate_admin);
		mImgBtn03 = (ImageView) findViewById(R.id.nate_src);
		mSpin = (Spinner) findViewById(R.id.allSpin);
		cateLayout = (LinearLayout)getLayoutInflater().inflate(R.layout.list, null);
		cateList = (ListView) cateLayout.findViewById(R.id.listView);
		ideaLayout = (LinearLayout)getLayoutInflater().inflate(R.layout.idea_list, null);
		ideaList = (ListView) ideaLayout.findViewById(R.id.ideaListView);
	}
	
	private void setEvent(){
		mSpin.setOnItemSelectedListener(new OnItemSelectedListener() {            
		     public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {                
		    	 spinCheck = position;	        	 
		    	 Cursor c = selectCategory();
		    	 showCategory2(c);
	        	 
	        	 Cursor c2 = selectWhereItem(aListCategory.get(position).toString());
	        	 showWhereItem(c2);
	        	 allAdapter.notifyDataSetChanged();
	         } 
	         public void onNothingSelected(AdapterView<?> parent) { } 
		});
		
		mImgBtn01.setOnClickListener(mOnClickListener);
		mImgBtn02.setOnClickListener(mOnClickListener);
		mImgBtn03.setOnClickListener(mOnClickListener);
	}
	
	private void initDataBase(){
		c = selectCategory();	//카테고리 가져올 쿼리문
   	 	showCategory2(c);		//스피너에 뿌려질 메서드
   	 	
   	 	if(aListCategory.size() > 0){
   	 		Cursor c2 = selectWhereItem(aListCategory.get(0).toString());
   	 		showWhereItem(c2);
   	 	}   	 	
		
   	 	c3 = selectAllItem(); 		//모든 IDEA 가져올 쿼리문
		showIdea2(c3); 				//다이얼로그에 뿌려질 메서드
		cursor2 = selectCategory(); //모든 카테고리 가져올 쿼리문
		showCategory(cursor2); 		//다이얼로그에 뿌려질 메서드
		cateCursor = selectCategory(db); //카테고리에 뿌려줄 쿼리문		
		
		String [] from = new String[]{"catename"};
		int [] to = new int[]{android.R.id.text1};
		simpleAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cateCursor, from, to);				
		simpleAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mSpin.setAdapter(simpleAdapter);
		
		allAdapter = new AllIdeaAdapter(this, mAllIdeaArray);
		mListIdeaView.setAdapter(allAdapter);
	}
	
//	@Override
//	public void onClick(View v) {
//		int id = v.getId();
//		
//		switch (id) {
//		case R.id.ideaListBtnDel:
//			db = sql.getWritableDatabase();					
//			if(ideaAdapter.alist2.size() > 0){
//				for(int i = 0; i < ideaAdapter.alist2.size(); i++){
//					db.delete(IT_sql.IDEA_TBL, "_id=?", new String[]{ideaAdapter.alist2.get(i).toString()});
//				}
//				Toast.makeText(IdeaAll.this, "삭제 되었습니다.", Toast.LENGTH_SHORT).show();
//				dismissDialog(Global.DIALOG_IDEA_STATUS);
//				showDialog(Global.DIALOG_IDEA_STATUS);
//				if(aListCategory.size() != 0){
//					Cursor c2 = selectWhereItem(aListCategory.get(0).toString());
//		   	 		showWhereItem(c2);
//		   	 		allAdapter.notifyDataSetChanged();
//				}else{						
//					mAllIdeaArray.add(new AllIdea("표시할 아이디어가 없습니다.", "", ""));
//					allAdapter.notifyDataSetChanged();
//				}
//			}else{
//				new CustomToast(mContext, "삭제할 대상이 없습니다.").show();
//			}
//			break;
//
//			
//		case R.id.ideaListCloseDel:
//			if(dialog != null)
//				dialog.dismiss();
//			break;
//		default:
//			break;
//		}
//	}
	
	private OnClickListener mOnClickListener = new OnClickListener() {
			
		@Override
			public void onClick(View v) {
				if(v.getId() == R.id.idea_admin){
					//TODO Fragment Dialog 로 변경.
					ideaAdapter = new CustomIdeaAdapter(mContext, mIdeaArray);
					dialog = new CustomDialogFragment(mContext, R.layout.idea_list, "아이디어 관리", ideaAdapter, mOnClickListener);
					dialog.show(manager, "IDEA_STATUS");
										
				}else if(v.getId() == R.id.cate_admin){
					//showDialog(Global.DIALOG_CATEGORY_STATUS);
					
				}else if(v.getId() == R.id.nate_src){
					if(nateSearch.size() == 3){
						Intent intent = new Intent(IdeaAll.this, NateWeb.class);
						intent.putExtra("ITEM1", nateSearch.get(0));
						intent.putExtra("ITEM2", nateSearch.get(1));
						intent.putExtra("ITEM3", nateSearch.get(2));					
						nateSearch.clear();					
						startActivity(intent);				
					}
					else if(nateSearch.size() == 0){
						new CustomToast(mContext, "조합된 검색어가 없습니다.").show();
					}
					
				}
				
				int id = v.getId();
				
				switch(id){
					case R.id.ideaListBtnDel:
						db = sql.getWritableDatabase();					
						if(ideaAdapter.alist2.size() > 0){
							for(int i = 0; i < ideaAdapter.alist2.size(); i++){
								db.delete(IT_sql.IDEA_TBL, "_id=?", new String[]{ideaAdapter.alist2.get(i).toString()});
							}
							new CustomToast(mContext, "삭제 되었습니다.").show();
							//TODO
							//1. Dialog ui 갱신
							//2. 전체아이디어 ListView 갱신
							
							//전체 아이디어 ListView 갱신
//							if(aListCategory.size() != 0){
//								Cursor c2 = selectWhereItem(aListCategory.get(0).toString());
//					   	 		showWhereItem(c2);
//					   	 		allAdapter.notifyDataSetChanged();
//							}else{				
//								mAllIdeaArray.add(new AllIdea("표시할 아이디어가 없습니다.", "", ""));
//								allAdapter.notifyDataSetChanged();
//							}
							
						}else{
							new CustomToast(mContext, "삭제할 대상이 없습니다.").show();
						}
						
						break;
						
					case R.id.ideaListCloseDel:
						if(dialog != null)
							dialog.dismiss();
						break;
				}
			}
	};
	
	public Cursor selectAllItem(){		
		db = sql.getWritableDatabase();
		Cursor cursor = db.query(IT_sql.IDEA_TBL, null, null, null, null, null, null);		
		startManagingCursor(cursor);
		return cursor;
	}
	
	public Cursor selectCategory(SQLiteDatabase db){
		Cursor cursor = db.query(IT_sql.CATEGORY_TBL, null, null, null, null, null, null);
		startManagingCursor(cursor);
		return cursor;
	}
	
	//카테고리에 해당하는 아이디어 보기
	private void showIdea2(Cursor cursor){		
		while(cursor.moveToNext()){
			int cateCheck = cursor.getInt(0);
			String idea1 = cursor.getString(2);
			String idea2 = cursor.getString(3);
			String idea3 = cursor.getString(4);
			mIdeaArray.add(new IdeaData(idea1, idea2, idea3, cateCheck));
		}		
	}
		
	//카테고리 추가 쿼리문
	private void addCategory(String cate){		
		db = sql.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put("catename", cate);
		db.insertOrThrow(IT_sql.CATEGORY_TBL, null, values);		
	}
	
	//셀렉트 모든 카테고리 쿼리문
	public Cursor selectCategory(){		
		db = sql.getWritableDatabase();
		Cursor cursor = db.query(IT_sql.CATEGORY_TBL, null, null, null, null, null, null);		
		startManagingCursor(cursor);		
		return cursor;
	}

	private void showCategory(Cursor cursor){		
		while(cursor.moveToNext()){
			int cateCheck = cursor.getInt(0);
			String category = cursor.getString(1);
			mCateArray.add(new Data(category, cateCheck));
		}		
	}	
	
	private void showCategory2(Cursor cursor){		
		while(cursor.moveToNext()){			
			String category = cursor.getString(1);
			aListCategory.add(category);
		}		
	}
	
	//카테고리에 해당하는 쿼리문
	private Cursor selectWhereItem(String aa){		
		db = sql.getWritableDatabase();
		Cursor cursor;
		
		if(aa.equals("전체")){
			cursor = db.query(IT_sql.IDEA_TBL, null, null, null, null, null, null);
			startManagingCursor(cursor);
		}else{
			String selection = "catename=?";		
			cursor = db.query(IT_sql.IDEA_TBL, null, selection, new String [] {aa}, null, null, null);
			startManagingCursor(cursor);
		}
		
		return cursor;
	}
	
	//카테고리에 해당하는 ITEM 보여주기
	private void showWhereItem(Cursor cursor){		
		mAllIdeaArray.clear(); //먼저 mAllIdeaArray의 내용을 지워주고 시작 : Data가 계속 쌓이므로 지워준다.
		
		while(cursor.moveToNext()){			
			String item1 = cursor.getString(2);
			String item2 = cursor.getString(3);
			String item3 = cursor.getString(4);						
			mAllIdeaArray.add(new AllIdea(item1, item2, item3));
		}		
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
				
		switch(id) {
		//카테고리 관리
		case Global.DIALOG_CATEGORY_STATUS :{					
			builder.setTitle("카테고리 관리");			
			cateLayout = (LinearLayout)getLayoutInflater().inflate(R.layout.list, null);
			cateList = (ListView) cateLayout.findViewById(R.id.listView);
			
			cursor2 = selectCategory(); //모든 카테고리 가져올 쿼리문
			showCategory(cursor2); //다이얼로그에 뿌려질 메서드
			
			adapter = new CustomAdapter(this, mCateArray);
			adapter.notifyDataSetChanged();
			cateList.setAdapter(adapter);			
			builder.setView(cateLayout);
				
			Button addBtn = (Button) cateLayout.findViewById(R.id.listBtnAdd);
			Button delBtn = (Button) cateLayout.findViewById(R.id.listBtnDel);
			Button closeBtn = (Button) cateLayout.findViewById(R.id.listBtnClose);
						
			//카테고리추가
			addBtn.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					showDialog(Global.DIALOG_CATEGORY_ADD);
					dismissDialog(Global.DIALOG_CATEGORY_STATUS);
				}
			});
			
			//카테고리삭제
			delBtn.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					
					db = sql.getWritableDatabase();
					
					if(adapter.alist.size() != 0){
						for(int i = 0; i < adapter.alist.size(); i++){
							db.delete(IT_sql.CATEGORY_TBL, "_id=?", new String[]{adapter.alist.get(i).toString()});						
						}					
						new CustomToast(mContext, "삭제 되었습니다.").show();
						dismissDialog(Global.DIALOG_CATEGORY_STATUS);
						showDialog(Global.DIALOG_CATEGORY_STATUS);
						
						c = selectCategory();
				   	 	showCategory2(c);
				   	 	simpleAdapter.notifyDataSetChanged();
					}else{
						new CustomToast(mContext, "삭제할 대상이 없습니다.").show();
					}
				}
			});
			
			//카테고리 닫기
			closeBtn.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					dismissDialog(Global.DIALOG_CATEGORY_STATUS);
				}
			});
			
			return builder.create();
		 }
		
		//카테고리 추가
		case Global.DIALOG_CATEGORY_ADD:{							
			builder.setTitle("카테고리 추가");
			edit = (EditText)getLayoutInflater().inflate(R.layout.dialogedit, null);			
			builder.setView(edit);
			builder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					String cateEdit = edit.getText().toString().trim();
					
					if(cateEdit == "" || cateEdit.equals("") || cateEdit ==  null){
						new CustomToast(mContext, "카테고리를 입력해 주세요.").show();
				   	 	
					}else{
						addCategory(edit.getText().toString());
						new CustomToast(mContext, "추가 되었습니다.").show();
						edit.setText("");
						showDialog(Global.DIALOG_CATEGORY_STATUS);
						dismissDialog(Global.DIALOG_CATEGORY_ADD);
						c = selectCategory(); 				//카테고리 가져올 쿼리문
						showCategory2(c); 					//스피너에 뿌려질 메서드
						simpleAdapter.notifyDataSetChanged();
					}
				}
			});
			
			return builder.create();
		}
		
		//아이디어관리
		case Global.DIALOG_IDEA_STATUS :{					
			builder.setTitle("아이디어 관리");
			ideaLayout = (LinearLayout)getLayoutInflater().inflate(R.layout.idea_list, null);
			ideaList = (ListView) ideaLayout.findViewById(R.id.ideaListView);
			
			c3 = selectAllItem();	//모든 IDEA 가져올 쿼리문
			showIdea2(c3); 			//다이얼로그에 뿌려질 메서드
			
			ideaAdapter = new CustomIdeaAdapter(this, mIdeaArray);
			ideaAdapter.notifyDataSetChanged();
			ideaList.setAdapter(ideaAdapter);			
			builder.setView(ideaLayout);						
			Button delBtn = (Button) ideaLayout.findViewById(R.id.ideaListBtnDel);
			Button closeBtn = (Button) ideaLayout.findViewById(R.id.ideaListCloseDel);
			
			delBtn.setOnClickListener(mOnClickListener);
			closeBtn.setOnClickListener(mOnClickListener);
			
			return builder.create();
		 }
		
		case Global.DIALOG_SHAKE_IDEA :{					
			builder.setTitle("Random IDEA");			
			dText = (TextView)getLayoutInflater().inflate(R.layout.shake_idea, null);						
			builder.setView(dText);			
			dText.setText(nateSearch.get(0).toString());			
			builder.setPositiveButton("닫기", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					//code
					dismissDialog(Global.DIALOG_SHAKE_IDEA);
				}
			});
			
			return builder.create();
		 }
		}//switch End
		
		return super.onCreateDialog(id);
	}
	
	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {	
		super.onPrepareDialog(id, dialog);
		
		switch(id) {
			//카테고리 관리
			case Global.DIALOG_CATEGORY_STATUS :{					
				if(mCateArray.size() != 0){
					mCateArray.clear();
					cursor2 = selectCategory(); //모든 카테고리 가져올 쿼리문
					showCategory(cursor2); //다이얼로그에 뿌려질 메서드
					
					adapter = new CustomAdapter(this, mCateArray);
					adapter.notifyDataSetChanged();
					cateList.setAdapter(adapter);					
					
					cateCursor = selectCategory(db); //카테고리에 뿌려줄 쿼리문
					String [] from = new String[]{"catename"};
					int [] to = new int[]{android.R.id.text1};
					simpleAdapter = new SimpleCursorAdapter(this, 
							android.R.layout.simple_spinner_item, cateCursor, from, to);
					simpleAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					simpleAdapter.notifyDataSetChanged();
					mSpin.setAdapter(simpleAdapter);
				}
			}
			
			//아이디어 관리
			case Global.DIALOG_IDEA_STATUS :{							
				if(mIdeaArray.size() != 0){
					mIdeaArray.clear();
					c = selectCategory();
			   	 	showCategory2(c);
					c3 = selectAllItem(); //모든 IDEA 가져올 쿼리문
					showIdea2(c3); //다이얼로그에 뿌려질 메서드				
					
					ideaAdapter = new CustomIdeaAdapter(this, mIdeaArray);
					ideaAdapter.notifyDataSetChanged();
					ideaList.setAdapter(ideaAdapter);
				}
			}
			
			case Global.DIALOG_SHAKE_IDEA :{
				if(nateSearch.size() !=0){ 
				dText.setText(nateSearch.get(0).toString() + "  "+ nateSearch.get(1).toString() + "  " +
						nateSearch.get(2).toString());
				}
			}
		}
	}
	
	public void upDate(){
		removeDialog(Global.DIALOG_CATEGORY_STATUS);
	}
	
	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) { } //센서의 정확도가 변경될 때 호출
	
	int x,y,z; //센서 측정 위한 x,y,z 좌표값 담을 int 변수
	int xFlag = 0;
	
	@Override
	public void onSensorChanged(SensorEvent event) { //측정값이 변경될 때 호출
		synchronized (this) {
			   //Sensor sensor = event.sensor;
			   
			   int max = 4;
			   int min = 1; 
			   
			   Vibrator vibe = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
			   
	           x = Math.round(event.values[0]);
	           y = Math.round(event.values[1]);
	           z = Math.round(event.values[2]);
			   	           
	           if(x > max && xFlag == 0){
//	        	   Log.e("TA" , "x1 = " + x);
	        	   
	        	   xFlag = 1;
	        	   
	        	    if(nateSearch.size() != 0){
						nateSearch.clear();
					}
						            	
	            	if(mAllIdeaArray.size() != 0){
	            		int n = (int)(Math.random() * mAllIdeaArray.size());
						int n2 = (int)(Math.random() * mAllIdeaArray.size()); 
						int n3 = (int)(Math.random() * mAllIdeaArray.size()); 
						String idea1 = mAllIdeaArray.get(n).getAllIdea1();
						String idea2 = mAllIdeaArray.get(n2).getAllIdea2();
						String idea3 = mAllIdeaArray.get(n3).getAllIdea3();	            	
	            	
						vibe.vibrate(200); // 진동 설정
//						shakeText.setText(idea1 + ", " + idea2 + ", " + idea3);
						nateSearch.add(idea1);
						nateSearch.add(idea2);
						nateSearch.add(idea3);
						showDialog(Global.DIALOG_SHAKE_IDEA);
						
	            	}else{
	            		vibe.vibrate(100); // 진동 설정
	            		Toast.makeText(IdeaAll.this, "아이디어가 없습니다.", Toast.LENGTH_SHORT).show();
	            	}
	           
	           }else if(x < min){
//	        	   	Log.e("TA" , "x2 = " + x);
           			xFlag = 0;        		
           	}			            
		}		
	}

	@Override
	protected void onStop() {
		sensorManager.unregisterListener(this);
		super.onStop();
	}
	
	@Override
    protected void onResume() {
        super.onResume();        		
        
        List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER)  ;
        sensorManager.registerListener(this, sensors.get(0),
          SensorManager.SENSOR_ACCELEROMETER|
             SensorManager.SENSOR_DELAY_FASTEST
        );
        
        sensorManager.registerListener(this, sensors.get(0),
          SensorManager.SENSOR_ORIENTATION |
          SensorManager.SENSOR_DELAY_FASTEST
        );
    }
	
	@Override
	public void onBackPressed() {
		super.onBackPressed();
		finish();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		db.close();
	}
}